<template>
  <div class="app-container">
    <!-- 头部搜索 -->
    <el-row class="header">
      <el-col :span="8">
        <el-input v-model="queryForm.query" placeholder="用户名" clearable />
        <el-button type="primary" :icon="Search" round @click="initDate"
          >搜索</el-button
        >
        <el-button type="success" :icon="Plus" round @click="handlerDialogValue"
          >新增</el-button
        >
        <el-popconfirm
          title="你确定要删除所选的所有内容吗?"
          @confirm="handleDelete(null)"
        >
          <template #reference>
            <el-button
              type="danger"
              :disabled="deleteState"
              :icon="Delete"
              round
              >批量删除</el-button
            >
          </template>
        </el-popconfirm>
      </el-col>
    </el-row>
    <!-- 主体部分 -->
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="avatar" label="头像" width="80" align="center">
        <template v-slot="scope">
          <img
            :src="getServerUrl() + 'image/userAvatar/' + scope.row.avatar"
            width="50"
            height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="100"
        align="center"
      />
      <el-table-column
        prop="roleList"
        label="拥有角色"
        width="200"
        align="center"
      >
        <template v-slot="scope">
          <!-- {{ scope.row }} -->
          <el-tag
            size="small"
            type="warning"
            v-for="item in scope.row.roleList"
          >
            {{ item.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" align="center" />
      <el-table-column
        prop="phonenumber"
        label="手机号"
        width="120"
        align="center"
      />
      <el-table-column prop="status" label="状态？" width="200" align="center">
        <template v-slot="{ row }">
          <el-switch
            v-model="row.status"
            @change="statusChangeHandle(row)"
            active-text="正常"
            inactive-text="禁用"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="200"
        align="center"
      />
      <el-table-column
        prop="loginDate"
        label="最后登录时间"
        width="200"
        align="center"
      />
      <el-table-column prop="remark" label="备注" />
      <el-table-column
        prop="action"
        label="操作"
        width="400"
        fixed="right"
        align="center"
      >
        <template v-slot="scope">
          <!-- 分配权限 -->
          <el-button
            type="primary"
            :icon="Tools"
            @click="handleRoleDialogValue(scope.row.id, scope.row.roleList)"
            >分配角色</el-button
          >
          <!-- 修改按钮 -->
          <el-button
            v-if="scope.row.username != 'java1234'"
            type="primary"
            :icon="Edit"
            @click="handlerDialogValue(scope.row.id)"
          />
          <!-- 删除按钮 -->
          <el-popconfirm
            v-if="scope.row.username != 'java1234'"
            title="您确定要删除这条记录吗？"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete">Del</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.username != 'java1234'"
            title="您确定要对这个用户重置密码吗？"
            @confirm="handleResetPassword(scope.row.id)"
          >
            <template #reference>
              <el-button type="warning" :icon="RefreshRight"
                >重置密码</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页标签 -->
    <el-pagination
      v-model:current-page="queryForm.current"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 自定义弹出修改或新增Dialog -->
    <Dialog
      v-model="dialogFormVisible"
      :dialogFormVisible="dialogFormVisible"
      :id="id"
      :dialogTitle="dialogTitle"
      @initDate="initDate"
    />

    <!-- 弹出权限修改方法 -->
    <RoleDialog
      v-model="roleDialogVisible"
      :roleDialogVisible="roleDialogVisible"
      :id="id"
      :checkedUserRoles="roleList"
      @initDate="initDate"
    />
  </div>
</template>
  <script setup>
import {
  Search,
  Plus,
  Edit,
  Delete,
  RefreshRight,
} from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import requestUtil, { getServerUrl } from "@/util/request";
import Dialog from "./components/DiaLog.vue";
import RoleDialog from "./components/RoleDialog.vue";
import { ElMessage } from "element-plus";
let tableData = ref([]);
let total = ref(0);
let queryForm = ref({
  query: "",
  current: 1,
  pageSize: 10,
});

// 初始化数据
let initDate = async () => {
  const result = await requestUtil.post("user/list", queryForm.value);
  // console.log(result);
  tableData.value = result.data.userList;
  total.value = result.data.total;
};
initDate();

//分页功能实现
//查询条数发生变化
let handleSizeChange = (pageSize) => {
  queryForm.value.current = 1;
  queryForm.value.pageSize = pageSize;
  initDate();
};

let handleCurrentChange = (currentPage) => {
  queryForm.value.current = currentPage;
  initDate();
};

//TODO  Dialog add功能
let dialogFormVisible = ref(false); //打开弹窗
let id = ref("");
let dialogTitle = ref("用户新增"); //弹窗标题

let handlerDialogValue = (userId) => {
  // console.log(userId);
  if (userId) {
    id.value = userId;
    dialogTitle.value = "用户修改";
  } else {
    id.value = "";
    dialogTitle.value = "用户新增";
  }
  dialogFormVisible.value = true;
};

//删除用户操作
const deleteState = ref(true);
let multipleSelection = reactive({
  data: [],
});

//ids复选框
const handleSelectionChange = (val) => {
  console.log(val);
  multipleSelection.data = val;
  deleteState.value = multipleSelection.data.length == 0;
};

//执行删除操作  判断是否为多人删除或者单人删除
const handleDelete = async (id) => {
  var ids = [];
  if (id) {
    ids.push(id);
  } else {
    multipleSelection.data.forEach((selectItem) => {
      console.log(selectItem.id);
      ids.push(selectItem.id);
    });
  }
  console.log(ids);

  //开始删除
  const res = await requestUtil.post("user/delete", ids);
  if ((res.code = 20000)) {
    ElMessage({
      type: "success",
      message: res.message,
    });
    initDate();
  } else {
    ElMessage({
      type: "error",
      message: res.message,
    });
  }
};

//密码操作

//重置密码
let handleResetPassword = async (id) => {
  const res = await requestUtil.get(`user/resetPassword/${id}`);
  if (res.code == 20000) {
    ElMessage.success({
      type: "success",
      message: "重置成功！",
    });
  } else {
    ElMessage.success({
      type: "error",
      message: res.message,
    });
  }
};

//用户状态修改
let statusChangeHandle = async (user) => {
  const res = await requestUtil.get(
    `user/updateStatus/${user.id}/status/${user.status}`
  );
  if (res.code == 20000) {
    ElMessage.success({
      type: "success",
      message: "用户状态变更成功!",
    });
  } else {
    ElMessage.success({
      type: "error",
      message: res.message,
    });
  }
};

//分配角色 开启子组件Dialog 操作TODO
let roleDialogVisible = ref(false); //打开弹窗
let roleList = ref([]);
let handleRoleDialogValue = (userid, roles) => {
  id.value = userid;
  roleList.value = roles;
  roleDialogVisible.value = true;
};
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 20px;
  .el-col {
    display: flex;
    .el-button {
      margin: 5px;
    }
  }
}
.app-container {
  padding: 0px;
  .el-pagination {
    display: flex;
    justify-content: flex-end;
  }
}
</style>